<template>
  <div id="app">
    <el-button type="primary" round @click="showScoreDialog = true">修改分数</el-button>
    <el-button type="warning" round @click="skipShiftDialogVisible = true">跳过排班</el-button>
    <el-button type="danger" round @click="savescheduleData()">保存排班</el-button>
    <el-calendar> <template #dateCell="{ date, data }">
        <div class="cell-content">
          <h3>{{ date.getMonth() + 1 + '月' + date.getDate() + '日' }}</h3>
          <ul>
            <li @click="updateShift('zaoban', date)" v-if="scheduleData[new Date(data.day).getDate()].zaoban"
              class="shift-zaoban" :class="{'highlight': isCurrentUserShift('zaoban', date)}">
              早班：{{ scheduleData[new Date(data.day).getDate()].zaoban }} </li>
            <li @click="updateShift('zhongban', date)" v-if="scheduleData[new Date(data.day).getDate()].zhongban"
              class="shift-zhongban" :class="{'highlight': isCurrentUserShift('zhongban', date)}">
              中班：{{ scheduleData[new Date(data.day).getDate()].zhongban }} </li>
            <li @click="updateShift('wanban', date)" v-if="scheduleData[new Date(data.day).getDate()].wanban"
              class="shift-wanban" :class="{'highlight': isCurrentUserShift('wanban', date)}">
              晚班：{{ scheduleData[new Date(data.day).getDate()].wanban }} </li>
            <li @click="updateShift('xiuxi', date)" v-if="scheduleData[new Date(data.day).getDate()].xiuxi"
              class="shift-xiuxi"> 休息：{{ scheduleData[new Date(data.day).getDate()].xiuxi }} </li>
            <li @click="updateShift('zhengchangban', date)"
              v-if="scheduleData[new Date(data.day).getDate()].zhengchangban" class="shift-zhengchangban"
              :class="{'highlight': isCurrentUserShift('zhengchangban', date)}">
              正常班：{{ scheduleData[new Date(data.day).getDate()].zhengchangban }} </li>
          </ul>
        </div>
      </template> </el-calendar>
    <!-- 新增的对话框 -->
    <el-dialog style="" :visible.sync="showScoreDialog" title="修改员工分数">
      <el-table :data="Object.keys(employeeScores).map(key => ({ key, value: employeeScores[key] }))"
        style="width: 100%">
        <el-table-column prop="key" label="员工编号" width="180"></el-table-column>
        <el-table-column prop="value" label="当前分数" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-input v-model="employeeScores[scope.row.key]" placeholder="请输入新的分数"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showScoreDialog = false">取消</el-button>
        <el-button type="primary" @click="saveScores(employeeScores)">保存</el-button>
      </div>
    </el-dialog>

    <!-- 新增的跳过排班对话框 -->
    <el-dialog :visible.sync="skipShiftDialogVisible" title="跳过排班">
      <el-date-picker v-model="selectedSkipDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd"></el-date-picker>
      <div slot="footer" class="dialog-footer">
        <el-button @click="skipShiftDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="skipShift">确认跳过</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getInfo,
    updateUser
  } from '@/api/login'

  export default {
    data() {
      return {
        scheduleData: null,
        selectedDate: '',
        selectedShift: '',
        employeeScores: {
          A: 7,
          B: 4,
          C: 9,
          D: 2,
          E: 5,
          F: 6,
          G: 8,
          H: 3,
          I: 1,
          J: 10,
          K: 6
        },
        showScoreDialog: false,
        skipShiftDialogVisible: false,
        selectedSkipDate: '',
        currentUser: '' // 当前用户
      };
    },
    created() {
      // 获取当前月份的天数
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      this.scheduleData = this.generateSchedule(year, month);
      console.log(this.scheduleData);

      getInfo().then(res => {
        this.currentUser = res.user.userName;
      });
    },
    methods: {
      isCurrentUserShift(shiftType, date) {
        const dateKey = new Date(date).getDate();
        const shiftValue = this.scheduleData[dateKey][shiftType];
        console.log(shiftValue);
        return shiftValue.includes(this.currentUser);
      },
      generateSchedule(days) {
        const schedule = {};
        const originalEmployees = ['A', 'B', 'C', 'D', 'E'];
        const newEmployeeGroups = [
          ['F', 'G'],
          ['H', 'I'],
          ['J', 'K']
        ];
        const shifts = ['早班', '中班', '晚班', '休息', '休息', '正常班', '正常班', '正常班', '正常班', '正常班', '正常班'];

        // 初始化员工状态
        const originalEmployeeShifts = {};
        originalEmployees.forEach(employee => {
          originalEmployeeShifts[employee] = 0; // 初始状态为 0（早班）
        });

        let newEmployeeIndex = 0;
        const newEmployeePrevDayShifts = new Array(6).fill(null); // 记录新员工前一天的班次
        const newEmployeeCurrentShifts = newEmployeeGroups.flat().reduce((acc, employee) => {
          acc[employee] = 0; // 初始状态为 0（早班）
          return acc;
        }, {});

        for (let day = 1; day <= days; day++) {
          schedule[day] = {
            zaoban: '',
            zhongban: '',
            wanban: '',
            xiuxi: '',
            zhengchangban: ''
          };

          // 分配原班次
          for (let i = 0; i < originalEmployees.length; i++) {
            const shift = shifts[(day + i) % 5];
            if (shift === '早班') {
              schedule[day].zaoban = originalEmployees[i];
            } else if (shift === '中班') {
              schedule[day].zhongban = originalEmployees[i];
            } else if (shift === '晚班') {
              schedule[day].wanban = originalEmployees[i];
            } else if (shift === '休息') {
              if (!schedule[day].xiuxi) {
                schedule[day].xiuxi = originalEmployees[i];
              } else {
                schedule[day].xiuxi += `,${originalEmployees[i]}`;
              }
            }
          }

          // 特殊处理周末 F 和 G 的休息
          if (day % 7 === 5 || day % 7 === 6) { // 周六和周日
            if (newEmployeeIndex < 2) { // 跳过 F 和 G
              newEmployeeIndex += 2; // 直接跳过 F 和 G
            }

            // 确保 F 和 G 被安排休息
            if (!schedule[day].xiuxi) {
              schedule[day].xiuxi = '';
            }
            schedule[day].xiuxi += `,F,G`;
          }

          // 分配新班次
          let assignedZaoban = false,
            assignedZhongban = false;
          let assignedNewEmployees = new Set();

          while (!assignedZaoban || !assignedZhongban) {
            const groupIndex = Math.floor(newEmployeeIndex / 2);
            const employee = newEmployeeGroups[groupIndex][newEmployeeIndex % 2];

            if (day % 7 === 5 || day % 7 === 6) { // 周六和周日
              if (employee === 'F' || employee === 'G') {
                newEmployeeIndex = (newEmployeeIndex + 1) % 6; // 循环使用新员工
                continue;
              }
            }

            if (!assignedNewEmployees.has(employee)) {
              // 根据当前班次状态分配今天的班次
              if (newEmployeeCurrentShifts[employee] === 0 && !assignedZaoban) {
                if (!schedule[day].zaoban) {
                  schedule[day].zaoban = employee;
                } else {
                  schedule[day].zaoban += `,${employee}`;
                }
                assignedZaoban = true;
                newEmployeeCurrentShifts[employee] = 1; // 下次上中班
              } else if (newEmployeeCurrentShifts[employee] === 1 && !assignedZhongban) {
                if (!schedule[day].zhongban) {
                  schedule[day].zhongban = employee;
                } else {
                  schedule[day].zhongban += `,${employee}`;
                }
                assignedZhongban = true;
                newEmployeeCurrentShifts[employee] = 0; // 下次上早班
              } else {
                // 如果没有上过早班或中班，则按默认顺序分配
                if (!assignedZaoban) {
                  if (!schedule[day].zaoban) {
                    schedule[day].zaoban = employee;
                  } else {
                    schedule[day].zaoban += `,${employee}`;
                  }
                  assignedZaoban = true;
                } else if (!assignedZhongban) {
                  if (!schedule[day].zhongban) {
                    schedule[day].zhongban = employee;
                  } else {
                    schedule[day].zhongban += `,${employee}`;
                  }
                  assignedZhongban = true;
                }
              }
              assignedNewEmployees.add(employee);
            }

            newEmployeeIndex = (newEmployeeIndex + 1) % 6; // 循环使用新员工
          }

          // 记录新员工今日班次以便明天判断
          newEmployeeGroups.flat().forEach((employee, index) => {
            if (schedule[day].zaoban.includes(employee)) {
              newEmployeePrevDayShifts[index] = '早班';
            } else if (schedule[day].zhongban.includes(employee)) {
              newEmployeePrevDayShifts[index] = '中班';
            } else if (schedule[day].wanban.includes(employee)) {
              newEmployeePrevDayShifts[index] = '晚班';
            } else {
              newEmployeePrevDayShifts[index] = null; // 或其他逻辑处理休息日
            }
          });

          // 更新员工状态
          originalEmployees.forEach(employee => {
            originalEmployeeShifts[employee] = (originalEmployeeShifts[employee] + 1) % 5;
          });

          // 最后安排正常班
          const remainingEmployees = newEmployeeGroups.flat().filter(employee =>
            !schedule[day].zaoban.includes(employee) &&
            !schedule[day].zhongban.includes(employee) &&
            !schedule[day].wanban.includes(employee) &&
            !schedule[day].xiuxi.includes(employee)
          );

          if (day % 7 === 5 || day % 7 === 6) { // 周六和周日
            if (remainingEmployees.length > 0) {
              schedule[day].xiuxi += `,${remainingEmployees.join(',')}`;
            }
          } else {
            if (remainingEmployees.length > 0) {
              schedule[day].zhengchangban = remainingEmployees.join(',');
            }
          }

          // 添加调试输出
          // console.log(`Generated Schedule for Day ${day}:`, schedule[day]);
        }

        return schedule;
      },
      updateShift(shiftType, date) {
        const day = date.getDate();
        const employeeList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];

        // 弹出一个选择员工的对话框
        this.$prompt('请输入该班次的员工名称', '修改员工', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: this.scheduleData[day][shiftType],
        }).then(({
          value
        }) => {
          const newPersonnel = value.split(',').filter(Boolean); // 分割并过滤空字符串

          // 更新选定班次的人员
          this.scheduleData[day][shiftType] = newPersonnel.join(',');

          // 获取当前日期的所有班次人员
          const allShifts = [
            ...this.scheduleData[day].zaoban.split(',').filter(Boolean),
            ...this.scheduleData[day].zhongban.split(',').filter(Boolean),
            ...this.scheduleData[day].wanban.split(',').filter(Boolean),
            ...this.scheduleData[day].zhengchangban.split(',').filter(Boolean)
          ];

          // 计算所有员工
          const allEmployees = employeeList;

          // 计算休息人员
          const restingEmployees = allEmployees.filter(employee => !allShifts.includes(employee));

          // 更新休息人员
          this.scheduleData[day].xiuxi = restingEmployees.join(',');

          this.$message({
            type: 'success',
            message: `已替换${date.getMonth() + 1}月${date.getDate()}日 ${shiftType} 班次的员工，并更新了休息人员`
          });
        });
      },
      saveScores(data) {
        data = this.employeeScores
        console.log(data);
        this.showScoreDialog = false;
      },
      skipShift() {
        if (this.selectedSkipDate) {
          const selectedDate = new Date(this.selectedSkipDate);
          const year = selectedDate.getFullYear();
          const month = selectedDate.getMonth() + 1; // 月份从0开始，所以需要加1
          const day = selectedDate.getDate();

          // 构建唯一的日期键
          const dateKey = `${year}-${month}-${day}`;

          // 更新 scheduleData
          if (this.scheduleData[day]) {
            this.scheduleData[day] = {
              skipped: true
            };
          } else {
            // 如果该日期不在 scheduleData 中，可以考虑添加一个新的条目
            this.scheduleData[day] = {
              skipped: true
            };
          }

          this.$message({
            type: 'success',
            message: `已跳过${this.selectedSkipDate}的排班`
          });

          this.skipShiftDialogVisible = false;
          this.selectedSkipDate = '';
        } else {
          this.$message({
            type: 'warning',
            message: '请选择一个日期'
          });
        }
      },
      savescheduleData() {
        this.$message({
          type: 'success',
          message: `已保存排班`
        });
        console.log(this.scheduleData);
      }
    }
  }

</script>


<style>
  .cell-content {
    text-align: left;
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .cell-content h3 {
    margin: 0;
    font-size: 1.1em;
    color: #333;
  }

  .cell-content ul {
    padding-left: 0;
    list-style: none;
    margin-top: 8px;
  }

  .cell-content li {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
    font-size: 0.9em;
    color: #666;
  }

  .cell-content .shift-zaoban {
    color: #28a745;
    /* 早班颜色 */
  }

  .cell-content .shift-zhongban {
    color: #007bff;
    /* 中班颜色 */
  }

  .cell-content .shift-wanban {
    color: #dc3545;
    /* 晚班颜色 */
  }

  .cell-content .shift-xiuxi {
    color: #6c757d;
    /* 休息颜色 */
  }

  .el-calendar-table td:hover .cell-content {
    background-color: aliceblue;
  }

  .el-calendar-table .is-today .cell-content {
    background-color: #ffecb3;
  }

  /* 保证单元格内的内容居中 */
  .el-calendar-table td .cell-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 230%;
  }

  /* 设置固定的单元格高度 */
  .el-calendar-table td {
    height: 180px;
    /* 增加单元格的高度 */
  }

  /* 日历头部样式 */
  .el-calendar-header {
    background-color: #f0f0f0;
    padding: 12px;
    border-bottom: 1px solid #e0e0e0;
  }

  .el-calendar-header .el-button {
    font-size: 16px;
    color: #333;
  }

  /* 日历表格样式 */
  .el-calendar-table {
    border-collapse: collapse;
    width: 100%;
  }

  .el-calendar-table__row .prev,
  .el-calendar-table__row .next {
    border: none;
    visibility: hidden;
  }

  .el-calendar-table__row .prev::before,
  .el-calendar-table__row .prev::after,
  .el-calendar-table__row .next::before,
  .el-calendar-table__row .next::after {
    border: none;
  }

  .highlight {
    background-color: yellow;
  }

</style>
